const express = require("express");
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const pushPaymentStatus = require('./ydapi.js')
const validCouponIds = ['69', '70', '114', '115', '116'];
const couponIds = ['69', '70'];
//mall/v1/order/accept
router.post("/v1/order/accept", async (req, res) => {
  let obj=req.body;
  let bodyJson=obj.contractRoot.body;
  console.log(888,bodyJson);
  let couponId=bodyJson.spu_id;
  if(!validCouponIds.includes(couponId)){
    res.send({
              contractRoot:{
                head:{},
                body:{
                  msg_type:"paystatussyncresp",
                  version:"1.0",
                  status:"1",
                  message:"券类型错误"
                },
              }
            });
  }else{
    let {total}=await utils.getSum({name:"t_new_order",where:`WHERE fromType="gxyd" and coupon_id ='69'`,res,req});
    if(couponId =='69' && total>=10200){
      res.send({
              contractRoot:{
                head:{},
                body:{
                  msg_type:"paystatussyncresp",
                  version:"1.0",
                  status:"1",
                  message:"券已达到上限值"
                },
              }
            });
    }else{
      let phone=bodyJson.order_phone;
      let accept_time=bodyJson.accept_time;
      let goodsJson=[];
      let vipType;
      if(couponId=='69'){
        goodsJson=[
          {
              productId:'69',
              iscoupon:1,
              skuName:"5元商城现金券",
              imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250528110846-Group%2020%402x.png",
              discountType:'4',
              price:'2',
              orinprice:'5',
              inventory:'10000',
              buyNum:1,
          }
        ]
      }
      if(couponId=='70'){
        goodsJson=[
          {
              productId:'70',
              iscoupon:1,
              skuName:"88折商城优惠券",
              imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250528110900-Group%2024%402x.png",
              discountType:'5',
              price:'0.1',
              orinprice:'1',
              inventory:'10000',
              buyNum:1,
          }
        ]
      }
      if(couponId=='114'){
        vipType=5;
        goodsJson=[
          {
              productId:'114',
              iscoupon:0,
              skuName:"零食会员基础包(广西)",
              imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802200859-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(1).png",
              price:'10',
              orinprice:'1',
              inventory:'10000',
              buyNum:1,
          }
        ]
      }
      if(couponId=='115'){
        vipType=6;
        goodsJson=[
          {
              productId:'115',
              iscoupon:0,
              skuName:"零食会员精选包(广西)",
              imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802200958-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(2).png",
              price:'20',
              orinprice:'1',
              inventory:'10000',
              buyNum:1,
          }
        ]
      }
      if(couponId=='116'){
        vipType=7;
        goodsJson=[
          {
              productId:'116',
              iscoupon:0,
              skuName:"零食会员优选包(广西)",
              imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802201133-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(3).png",
              price:'30',
              orinprice:'1',
              inventory:'10000',
              buyNum:1,
          }
        ]
      }
      // if(couponId=='117'){
      //   vipType=4;
      //   goodsJson=[
      //     {
      //         productId:'117',
      //         iscoupon:0,
      //         skuName:"零食优选会员礼包",
      //         imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802201206-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(4).png",
      //         price:'0.1',
      //         orinprice:'1',
      //         inventory:'10000',
      //         buyNum:1,
      //     }
      //   ]
      // }
      let order_no=utils.getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
      let sql = "INSERT INTO t_new_order(order_id,phone,pay_time,total_price,total_discount,total_fee,coupon_id,goods_json,state,update_time,create_time,goodsIsOnlyCoupon,fromType) VALUES (?,?,?,?,?,?,?,?,?,now(),now(),?,'gxyd')";
        pool.query(sql, [order_no,phone,accept_time,goodsJson[0].orinprice,0,goodsJson[0].price,couponId,JSON.stringify(goodsJson),3,1], (err, result) => {
            if (err) return res.send(utils.returnData({code: -1,err,req}));
            //如果couponId属于特定值就维护会员权益
            //维护会员身份，更新user_vip表，会员到期时间，会员折扣权益
            if(!couponIds.includes(couponId)){
              let vipName;
              if(couponId=='114'){
                vipType=5;
                vipName="会员基础包(广西)";
              }
              if(couponId=='115'){
                vipType=6;
                vipName="会员精选包(广西)";
              }
              if(couponId=='116'){
                vipType=7;
                vipName="会员优选包(广西)";
              }
              //判断当前用户是否购买过同类型的会员，如果购买过，就更新会员到期时间，增加30天
              let sql = `SELECT * FROM user_vip WHERE phone = "${phone}" AND vip_type = "${vipType}"`;
              pool.query(sql, [],(err, result) => {
                  if (err) return res.send(utils.returnData({code: -1,err,req}));
                  if(result.length>0){
                    //更新会员到期时间，增加30天
                    let sql = `UPDATE user_vip SET vip_expiration_date = DATE_ADD(vip_expiration_date, INTERVAL 30 DAY) WHERE id = "${result[0].id}"`;
                    pool.query(sql, [],(err, result) => {
                      if (err) return res.send(utils.returnData({code: -1,err,req}));
                      res.send({
                        contractRoot:{
                          head:{},
                          body:{
                            msg_type:"paystatussyncresp",
                            version:"1.0",
                            status:"0",
                            message:"领取成功",
                            m_order_id:order_no,
                          },
                        }
                      });
                    });
                  }else{
                    //新增会员
                    let sql = `INSERT INTO user_vip (phone, vip_type,vip_name, create_time,vip_expiration_date) VALUES ("${phone}", "${vipType}","${vipName}", NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY))`;
                    pool.query(sql, [],(err, result) => {
                      if (err) return res.send(utils.returnData({code: -1,err,req}));
                      res.send({
                        contractRoot:{
                          head:{},
                          body:{
                            msg_type:"paystatussyncresp",
                            version:"1.0",
                            status:"0",
                            message:"领取成功",
                            m_order_id:order_no,
                          },
                        }
                      });
                    });
                  }
                  //不管是新增还是更新都要执行，会员送券方法
                  utils.sendCouponToUser(phone,vipType);
              });
            }else{
              //维护几种会员赠品，现金券，1张0.1一次性兑换券（分档次）
              let sql2 = `INSERT INTO user_coupon (phone,coupon_id,expiration_date,is_use,update_time,create_time) VALUES(?,?,?,?,now(),now());`;
              pool.query(sql2, [phone,couponId,null,0],(err, result) => {
                  if (err) return res.send(utils.returnData({code: -1,err,req}));
                  res.send({
                    contractRoot:{
                      head:{},
                      body:{
                        msg_type:"paystatussyncresp",
                        version:"1.0",
                        status:"0",
                        message:"领取成功",
                        m_order_id:order_no,
                      },
                    }
                  });
              });
            }
            //调用支付回调方法
                  // 使用示例
                  const orderExample = {
                    orderId: bodyJson.channel_order_id,
                    isPlatformOrder: true,
                    payOrg: "HFPAY",
                    payWay: 0,
                    payType: 2,
                    payTime: new Date(),
                    amount: 0,
                    spuId:couponId,
                    spuName:goodsJson[0].skuName,
                  };
                   setTimeout(() => {
                    // 执行推送
                    pushPaymentStatus(orderExample)
                      .then(result => console.log("推送结果:", result))
                      .catch(err => console.error("执行失败:", err));
                  }, 10000); // 10000毫秒 = 10秒
        });
      }
    }
});



module.exports = router;
